<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      canvas {
        border: 1px solid #000;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="600" height="600"></canvas>
    <script>
      "use strict";
      const canvas = document.querySelector("#myCanvas");
      const context = canvas.getContext("2d");
      class rect {
        x;
        y;
        r;
        speed;
        color;
        constructor(x, y, r, speed, color) {
          this.x = x;
          this.y = y;
          this.r = r;
          this.speed = speed;
          this.color = color;
        }

        draw() {
          context.beginPath();
          context.arc(this.x, this.y, this.r, 0, Math.PI * 2);
          context.fillStyle = this.color;
          context.fill();
        }
        move() {
          this.x += this.speed;
          if (this.x - this.r < 0 || this.x + this.r > canvas.width) {
            this.speed *= -1;
          }
          if (isHit()) {
            this.speed *= -1;
          }
          console.log(this.x);
        }
      }

      const rect1 = new rect(50, 100, 50, 2, "red");
      const rect2 = new rect(500, 100, 50, 5, "blue");

      function animate() {
        // 注意碰撞检测的清楚函数写在执行函数中不然只会画一个圆
        context.clearRect(0, 0, canvas.width, canvas.height);
        rect1.draw();
        rect1.move();
        rect2.draw();
        rect2.move();
        requestAnimationFrame(animate);
      }
      animate();

      function isHit() {
        return (
          rect1.x <= rect2.x + rect2.r * 2 && rect1.x + rect1.r * 2 >= rect2.x
        );
      }
    </script>
  </body>
</html>
